package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 远程调用 自定义拦截器
 *   1/加入到页面微服务
 */
public class FeignInterceptor implements RequestInterceptor {

    //拦截远程调用请求方法
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //RequestTemplate : 远程调用请求   请求头中缺少用户ID
        //1:能不能获取当前微服务的请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if(null != requestAttributes){
            HttpServletRequest request = requestAttributes.getRequest();
            if(null != request){
                String userId = request.getHeader("userId");
                if(!StringUtils.isEmpty(userId)){
                    requestTemplate.header("userId",userId);
                }
                String userTempId = request.getHeader("userTempId");
                if(!StringUtils.isEmpty(userTempId)){
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }
    }
}
